package com.example.app.validation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.Arrays;

/**
 * 枚举值验证器
 */
public class ValidEnumValidator implements ConstraintValidator<ValidEnum, String> {
    
    private Class<? extends Enum<?>> enumClass;
    private boolean ignoreCase;
    
    @Override
    public void initialize(ValidEnum constraintAnnotation) {
        this.enumClass = constraintAnnotation.enumClass();
        this.ignoreCase = constraintAnnotation.ignoreCase();
    }
    
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        
        return Arrays.stream(enumClass.getEnumConstants())
                .anyMatch(enumConstant -> {
                    String enumName = enumConstant.name();
                    return ignoreCase ? enumName.equalsIgnoreCase(value) : enumName.equals(value);
                });
    }
}